import React, { useState, useEffect } from 'react'
import { HashRouter } from 'react-router-dom'
import { Layout, Menu, theme, Button, Tooltip, Spin } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import {
  FileTextOutlined,
  HomeOutlined,
  SettingOutlined,
  VideoCameraOutlined,
  BarChartOutlined,
  LineChartOutlined,
  FireOutlined
} from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { MENU_ROUTE_MAP, getRouteTitle, type MenuKey } from './router/routes'
import AppRouter from './router'
import { AISettingsModal } from './components/AISettings'
import { StorageFactory } from '../services/storage'
import './App.css'

const { Header, Sider, Content } = Layout

// 检测当前平台
const isMacOS = navigator.userAgent.includes('Macintosh')

const menuItems: MenuProps['items'] = [
  {
    key: 'home',
    icon: <HomeOutlined />,
    label: '工作台',
  },
  {
    key: 'text',
    icon: <FileTextOutlined />,
    label: '文本稿件',
  },
  {
    key: 'storyboard',
    icon: <VideoCameraOutlined />,
    label: '分镜管理',
  },
  {
    key: 'data',
    icon: <BarChartOutlined />,
    label: '融媒数据',
    children: [
      {
        key: 'data-analytics',
        icon: <LineChartOutlined />,
        label: '数据分析',
      },
      {
        key: 'data-hotspot',
        icon: <FireOutlined />,
        label: '热点分析',
      },
    ],
  },
]

/**
 * 应用布局组件
 * 包含侧边栏菜单和主内容区域，集成路由导航功能
 */
const AppLayout: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [selectedKeys, setSelectedKeys] = useState<string[]>(['home'])
  const [openKeys, setOpenKeys] = useState<string[]>([])
  const [showAISettings, setShowAISettings] = useState(false)

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken()

  // 根据当前路由更新菜单选中状态
  useEffect(() => {
    const currentPath = location.pathname
    const menuKey = Object.entries(MENU_ROUTE_MAP).find(
      ([, path]) => path === currentPath
    )?.[0]

    if (menuKey) {
      setSelectedKeys([menuKey])
      // 如果是子菜单项，自动展开父菜单
      if (menuKey.startsWith('data-')) {
        setOpenKeys(['data'])
      }
    }
  }, [location.pathname])

  // 处理菜单点击事件
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    const route = MENU_ROUTE_MAP[key as MenuKey]
    if (route) {
      navigate(route)
    }
  }

  // 获取当前页面标题
  const currentTitle = getRouteTitle(location.pathname)

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider
        breakpoint="lg"
        collapsedWidth="0"
        theme="light"
        width={200}
      >
        <div className="logo">
          <h2>融媒智创工坊</h2>
        </div>
        <Menu
          mode="inline"
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onOpenChange={(keys) => setOpenKeys(keys)}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ height: '100%', borderRight: 0 }}
        />
      </Sider>
      <Layout>
        <Header
          className="app-header"
          style={{
            padding: 0,
            background: colorBgContainer,
            borderBottom: '1px solid #f0f0f0',
            // @ts-ignore - WebkitAppRegion is a valid CSS property for Electron
            WebkitAppRegion: 'drag',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingTop: isMacOS ? '8px' : '0',
            height: isMacOS ? '64px' : '56px'
          }}
        >
          <div style={{
            padding: isMacOS ? '0 24px 0 80px' : '0 24px',
            fontSize: '18px',
            fontWeight: 'bold',
            // @ts-ignore - WebkitAppRegion is a valid CSS property for Electron
            WebkitAppRegion: 'no-drag',
            userSelect: 'none'
          }}>
            {currentTitle}
          </div>
          <div style={{
            paddingRight: '24px',
            // @ts-ignore - WebkitAppRegion is a valid CSS property for Electron
            WebkitAppRegion: 'no-drag'
          }}>
            <Tooltip title="AI设置">
              <Button
                type="text"
                icon={<SettingOutlined />}
                onClick={() => setShowAISettings(true)}
              >
                AI设置
              </Button>
            </Tooltip>
          </div>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 0,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <AppRouter />
        </Content>
      </Layout>

      {/* AI设置弹窗 */}
      <AISettingsModal
        visible={showAISettings}
        onClose={() => setShowAISettings(false)}
      />
    </Layout>
  )
}

/**
 * 主应用组件
 * 提供HashRouter包装和应用布局
 * 负责初始化存储系统
 */
const App: React.FC = () => {
  const [storageReady, setStorageReady] = useState(false)
  const [storageError, setStorageError] = useState<string | null>(null)

  useEffect(() => {
    // 初始化存储系统
    const initStorage = async () => {
      try {
        console.log('[应用启动] 开始初始化存储系统...')
        await StorageFactory.initialize()

        const storageType = StorageFactory.getStorageType()
        const displayName = {
          'indexeddb': 'IndexedDB',
          'localstorage': 'LocalStorage',
          'unknown': '未知'
        }[storageType]
        console.log(`[应用启动] ✅ 存储系统初始化成功: ${displayName}`)
        console.log('[应用启动] 💡 配置存储: JSON文件 (主进程)')

        setStorageReady(true)
      } catch (error) {
        console.error('[应用启动] ❌ 存储系统初始化失败', error)
        setStorageError(error instanceof Error ? error.message : '未知错误')
        setStorageReady(true) // 继续加载应用,使用降级存储
      }
    }

    initStorage()
  }, [])

  // 存储初始化中
  if (!storageReady) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Spin size="large" />
        <div style={{ color: '#666' }}>正在初始化存储系统...</div>
      </div>
    )
  }

  // 存储初始化失败提示(仍然加载应用)
  if (storageError) {
    console.warn('[应用启动] 存储系统降级运行:', storageError)
  }

  return (
    <HashRouter>
      <AppLayout />
    </HashRouter>
  )
}

export default App